<!--
    group: 发票管理
    name: 开票列表
    item: 开票查询-子组件
-->
<template>
  <div>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" style="margin-bottom: 10px">
      <a-form layout="inline">
        <a-row :gutter="24" style="margin-top: 10px">
          <a-col :md="6" :lg="6" :xl="7" :xxl="4">
            <a-form-item label="企业名称">
              <a-input placeholder="请输入" v-model="filterList.entName" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :lg="6" :xl="7" :xxl="4">
            <a-form-item label="法人">
              <a-input placeholder="请输入" v-model="filterList.lisenceLegal" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="10">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" icon="search" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 10px" icon="reload" @click="handleReset">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
              </span>
          </a-col>
        </a-row>
        <div class="table-page-search-wrapper" v-show="toggleSearchStatus">
          <a-row :gutter="24">
            <a-col :md="6" :lg="6" :xl="7" :xxl="4">
              <a-form-item label="发票类型">
                <a-select  placeholder="请选择" v-model="filterList.taxType">
                  <a-select-option :value="''"> 请选择 </a-select-option>
                  <a-select-option :value="1">增值税专用发票</a-select-option>
                  <a-select-option :value="2">增值税普通发票</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :lg="6" :xl="7" :xxl="4">
              <a-form-item label="发票材质">
                <a-select  placeholder="请选择" v-model="filterList.taxMedium">
                  <a-select-option :value="''"> 请选择 </a-select-option>
                  <a-select-option :value="1">纸质</a-select-option>
                  <a-select-option :value="2">电子</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>

    <a-table bordered
             :loading="loading"
             :pagination="false"
             :rowKey="row => row.id"
             :row-selection="rowSelection"
             :columns="columns"
             :data-source="tableData"
             :scroll="{x:400,y:500}"
    >
      <!-- 字符串超长截取省略号显示-->
      <span slot="esContent" slot-scope="text">
        <j-ellipsis :value="text" :length="10" />
      </span>

      <!--发票类型 1-专票 2-普票-->
      <span slot="taxType" slot-scope="text,record">
        <!--taxMedium  1纸质 2电子-->
        <span v-if="text" :class="text === 1 ? 'd' : 'c'" style="margin-right: 5px">
          {{{1:'专票',2:'普票'}[text] || ''}}
        </span>

        <!-- 开票类型 1-传统票 2-数电票 3-混合票  -->
        <template v-if="record.ticketType == 1">
          <span v-if="record.taxMedium" :class="record.taxMedium === 1 ? 'a' : 'b'">
            {{{1:'纸质',2:'电子'}[record.taxMedium] || ''}}
          </span>
          <span v-if="record.taxMedium === 2 && record.imageType" class="doc" style="margin-left: 5px;">
            {{ record.imageType }}
          </span>
        </template>
        <span v-if="record.ticketType == 2" class="g">数电发票</span>
      </span>

      <!--状态-->
      <span slot="bizStatus" slot-scope="text,record">
        <a-tag :color="statusInfo.kstatusColor[text]">
          {{statusInfo.kstatusLabel[text]}}
        </a-tag>
      </span>

      <!--操作-->
      <span slot="action" slot-scope="text,record" class="table-action">
        <template v-if="record.bizStatus == 100">
          <a-button v-has="tabNum+'inq_inquern:click:sccg'" @click="deleteDraft(record)" type="link" class="red">删除草稿</a-button>
          <a-divider type="vertical" />
          <a-button v-has="tabNum+'inq_inquern:click:xq100'" @click="suppleMentary(record)" type="link">详情</a-button>
        </template>
        <template v-else>
          <template v-if="record.bizStatus < 105">
            <a-button v-has="tabNum+'inq_inquern:click:cxbsc'" @click="undoDelete(record)" type="link" class="red">{{ record.errorFlag > 1 ? '撤销' : '撤销并删除'}}</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 103">
            <a-button v-has="tabNum+'inq_inquern:click:bczl'" @click="suppleMentary(record)" type="link">补充资料</a-button>
          </template>
          <template v-if="record.bizStatus == 104">
            <a-button v-has="tabNum+'inq_inquern:click:yqhy'" @click="invitationValidationNew(record,1)" type="link" class="red" v-preventReClick>邀请验证</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 117">
            <a-button v-has="tabNum+'inq_inquern:click:cxjs'" @click.prevent="revokeEvent(record)" type="link" class="red" v-preventReClick>撤销</a-button>
            <a-divider type="vertical" />
            <a-button v-has="tabNum+'inq_inquern:click:js'" @click="singleBalance(record)" type="link" class="red" v-preventReClick>结算</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 118">
            <a-button v-has="tabNum+'inq_inquern:click:cxhy'" @click="invitationValidationNew(record,2)" type="link" class="red" v-preventReClick>撤销核验</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 105">
            <a-button v-has="tabNum+'inq_inquern:click:zfcx'" @click="paymentRevoke(record)" type="link" v-preventReClick>撤销</a-button>
            <a-divider type="vertical" />
            <a-button v-has="tabNum+'inq_inquern:click:zf'" @click="paymentOther(record)" type="link" v-preventReClick>支付</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 107 && record.taxMedium == 1">
            <!--纸质  确认寄送 , 电子 下载发票-->
            <a-button v-has="tabNum+'inq_inquern:click:qrjs'" @click="confirmDelivery(record.id)" type="link" class="red" v-preventReClick>确认寄送</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus == 110 && record.taxMedium == 2">
            <!--纸质  确认寄送 , 电子 下载发票-->
            <a-button v-has="tabNum+'inq_inquern:click:xzfp'" @click="invoiceDownload(record)" type="link" class="red">下载发票</a-button>
            <a-divider type="vertical" />
          </template>
          <template v-if="record.bizStatus != 103">
            <a-button v-has="tabNum+'inq_inquern:click:xz103'" @click="toDetails(record)" type="link">详情</a-button>
          </template>
        </template>
      </span>
    </a-table>
    <!--批量按钮-->
    <div v-if="!revokeFlagStatus" style="margin-top: 10px;">
      <!--      <a-button v-if="this.businessStatus > 101 && this.businessStatus < 105" @click="batchDetaleFun" type="primary" class="mLeft">批量删除</a-button>-->
      <a-button v-if="businessStatus == 105" v-has="tabNum+'inq_inquern:click:plzf'" @click="batchPaymentFun" type="primary" style=" margin: 0 5px;">批量支付</a-button>
      <a-button v-if="businessStatus == 117" v-has="tabNum+'inq_inquern:click:pljs'" @click="batchSettlement" type="primary" style=" margin: 0 5px;">批量结算</a-button>
      <a-button v-if="businessStatus == 117" v-has="tabNum+'inq_inquern:click:plcxjs'" @click="batchRevokeEvent" type="primary" style=" margin: 0 5px;">批量撤销</a-button>
      <a-button v-if="businessStatus == 104 || businessStatus == 118" v-has="tabNum+'inq_inquern:click:plyz'" @click="batchValidation" type="primary" style=" margin: 0 5px;">{{{104:'批量验证',118:'批量撤销核验'}[businessStatus]}}</a-button>
      <!-- 9inq_inquern:click:plsc -->
      <a-button v-if="businessStatus == 100" v-has="tabNum+'inq_inquern:click:plsc'"  @click="BatchDeleteDrafts" type="primary" style=" margin: 0 5px;">批量删除</a-button>

    </div>
    <a-pagination
      v-model="page.currentPage"
      :page-size-options="['5', '10', '20']"
      :show-total="total => `共 ${total} 条`"
      :total="page.totalCount"
      show-size-changer
      :page-size="page.pageSize"
      @showSizeChange="onSizeChange"
      @change="onPageChange"
    >
    </a-pagination>


    <!-------------------- 结算与批量结算  start ↓ --------------->
    <!-- 预估费用弹层（单笔和批量结算）1、无待支付订单 && 未跨阶梯 -->
    <InvoiceBalance :config="balanceConfig" :checkList="balanceCheckList" @balanceMethod="balanceMethod" />
    <!-- 有待支付订单选择弹层（单笔和批量结算）1、有待支付订单 && 未跨阶梯  2、有待支付订单 && 跨阶梯 -->
    <SettlementRemainPaid :config="bePaidConfig" :checkList="balanceCheckList" :toBePaidList="toBePaidList" @toBePaidMethod="toBePaidMethod" />
    <!-- 展示超限额等超额判断弹层 1、无待支付订单 && 超限额 （单笔结算） -->
    <InvoiceCoverPrompt :config="promptConfig" @fatherPromptMethod="fatherPromptMethod" @fatherPreserveMethod="fatherPreserveMethod" />
    <!--  展示超限额等超额判断弹层 1、无待支付订单 && 超限额 （批量结算） 2、有待支付订单 && 超限额 （单笔和批量结算） -->
    <InvoiceBatchOverLimit :config="overLimitConfig" :overLimitCheckList="overLimitCheckList" :toBePaidList="toBePaidList" @overLimitMethod="overLimitMethod" />
    <!-- 确认费用弹层
        1、无待支付订单 && 跨阶梯2、无待支付订单 && 超限额（下一步确认费用）
        3、有待支付订单 && 跨阶梯4、有待支付订单 && 超限额（下一步确认费用）
    -->
    <InvoiceBatchSettlement :config="batchConfig" :checkList="balanceCheckList" @batchMethod="batchMethod" />
    <!-- 变更征收方式弹层 -->
    <ChangeCollectionMethod v-if="entId" :entId="entId" :config="collectionConfig" @fatherBackMethod="fatherBackMethod" />
    <!-------------------- 结算与批量结算  end ↑ --------------->


    <!-------------------- 邀请验证与批量验证  start ↓ --------------->
    <!--邀请验证及二维码查看-->
    <InvitationCode
      :invitationShow="invitationShow"
      :inContent="inContent"
      :showCodeTitle="showCodeTitle"
      @handleCodeFather="handleCodeFather"
    />
    <InvitationCodeNew :event="icnEvent" :rowData="invitationCodeNewData" :oldData="currentRowData" :show="invitationNewShow"></InvitationCodeNew>
    <!-- 单组核验展示 -->
    <SingleDataVerification :dataType="dataType_" :event="icnEvent" :rowData="singleDataVerificationData" :show="singleInvitationNewShow"></SingleDataVerification>
    <!--批量验证-->
    <BatchVerification :event="icnEvent" :rowData="batchVerificationDataList" :show="batchVerificationNewShow"></BatchVerification>
    <a-modal
      :width="800"
      :footer="null"
      v-model="invitationVisible"
    >
      <h3>验证邀请</h3>
      <p>我们将向下列用户发送发票认证，请确认发送对象！</p>

      <a-table bordered
               :pagination="false"
               :columns="verificationColumns"
               :data-source="verificationList"
               :scroll="{y:300}"
      >
      </a-table>
      <p style="text-align: center;margin-top: 20px;">
        <a-button class="btnsLarge" type="primary" @click="next">下一步</a-button>
      </p>
    </a-modal>
    <!-------------------- 邀请验证与批量验证  end ↑ --------------->

    <!-- 撤销开票申请 -->
    <a-modal
      :width="revokeConfig.width"
      :title="revokeConfig.title"
      :visible="revokeConfig.visible"
      @cancel="revokeCancelEvent"
      :footer="null"
    >
      <p style="font-weight: bold;">企业法人已完成本次开票核验，若撤销需要法人本人核验完成撤销确认！</p>
      <p>撤销核验完成后，本条数据将进入草稿箱，若需要再次开票，需要<font color="#f01500"><b>重新签署</b></font>业务说明书，请问您确认本次撤销操作吗？</p>
      <br/>
      <p><div style="display: flex; justify-content: center; align-items: center;">
      <a-button :loading="revokeConfig.CRloading" type="primary" block style="margin: 0 10px;" @click.prevent="confirmRevocation"> 确认撤销 </a-button>
      <a-button block style="margin: 0 10px;" @click.prevent="revokeCancelEvent">暂不撤销</a-button>
    </div></p>
    </a-modal>
    <InvitationVerification v-bind="ivConfig" :event="IVEvent"></InvitationVerification>

    <!--支付撤销-->
    <PaymentRevocation
      :config="payRevokeConfig"
      :payCheckList="payCheckList"
      @settlePayMethod="settlePayMethod"
    />

    <!--下载发票-->
    <InvoiceDownloadFormat :config="downloadFormatInfo" @handleInvoiceCancle="handleInvoiceCancle" />

    <!--删除草稿,撤销并删除,邀请验证,发送成功,订单创建成功,订单创建失败-->
    <ModalCurrency :config="undoConfig" @fatherMethod="fatherMethod" />

    <!-------------------------------------------------------------  首次开票金额限制弹层提示 ↓   ---------------------------------------------->
    <AmountLimitPrompt :config="excessConfig" />


    <!-------------------- 选择发票领用数量弹层（作废）--------------->
    <UageInsufficient
      :isUseShow="undeleteInfo.isCollecteShow"
      v-if="ticketMargin && theData.taxType && theData.taxMedium"
      :ticketMargin="ticketMargin"
      :taxType="theData.taxType"
      :taxMedium="theData.taxMedium"
      :billUseNum="0"
      @handleUseFather="handleUseFather"
    />

  </div>
</template>

<script>
import { getTaxInvoiceList } from '@/api/invoiceAdminister'
import status from '@/utils/invoicingStatus'
import { accAdd, accSub, conversionBranch, conversionElement, cloneObject, percentageConverse } from '@/utils/util'
import UageInsufficient from '@views/invoice/common/usageInsufficient.vue'
//页面事件处理JS引入
import NewInvoiceCommon from '@views/invoice/invoiceQueryItem/newInvoiceCommon'
import OtherButtonEvents from '@views/invoice/invoiceQueryItem/otherButtonEvents'
import BatchVerification from '@views/invoice/invoiceQueryItem/batchVerification'
import Balance from '@views/invoice/invoiceQueryItem/balance'
import AmountLimitPrompt from '@views/invoice/common/amountLimitPrompt.vue'
import useBatchDelete from './hooks/useBatchDelete'

export default {
  name: "invoiceQueryItem",
  // inject: ['reload'],
  props: ['businessStatus','goPageEvent','pageKey','tabNum'],
  mixins: [NewInvoiceCommon,OtherButtonEvents,BatchVerification,Balance,useBatchDelete],
  components: {
    AmountLimitPrompt,
    UageInsufficient,
  },
  data(){
    return{
      id: null,   //发票id
      statusInfo: status,
      toggleSearchStatus: false,
      filterList: {},
      loading: false,  //表格加载
      //表格分页
      page: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示条数
        totalPage: 0, // 总页数
        totalCount: 0, // 总条数
        params: {}, // 查询参数对象
        list: [], // 数据
      },
      tableData: [],
      columns: [
        {
          title: '订单编号',
          dataIndex: 'id',
          width: 120,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '开票公司',
          dataIndex: 'taxTitle',
          scopedSlots: {customRender: 'esContent'},
          ellipsis: true,
          width: 200,
          align: 'center'
        },
        {
          title: '企业负责人',
          dataIndex: 'lisenceLegal',
          ellipsis: true,
          width: 120,
          align: 'center'
        },
        {
          title: '发票类型',
          dataIndex: 'taxType',
          width: 160,
          scopedSlots: {customRender: 'taxType'},
          ellipsis: true,
          align: 'center'
        },
        {
          title: '开票金额',
          dataIndex: 'amount',
          customRender: (text,record) => {
            if (text != null){
              return Math.round(text * 100)/10000 + '元'
            }else {
              return '-'
            }
          },
          width: 130,
          align: 'center'
        },
        {
          title: '购买方',
          dataIndex: 'entName',
          scopedSlots: {customRender: 'esContent'},
          ellipsis: true,
          width: 200,
          align: 'center'
        },
        {
          title: '提交时间',
          dataIndex: 'createTime',
          width: 180,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'bizStatus',
          scopedSlots: {customRender: 'bizStatus'},
          width: 120,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
          align: 'center',
          fixed:'right',
          width: 240
        },
      ],

      selectedRowKeys: [],  //批量发布数据id
      selectedRows: [],  //批量发布数据
      entIdList:[],
      entId: null,  //企业id

      //首次开票金额限制弹层
      excessConfig: {
        width: '650px',
        visible: false,    //modal展示状态
        modalTitle: '',   //modal层的标题
        title: '首次开票金额不能超过您核定额度的1/3！',     //标题
        content: '您的核定额度为：月核定额度/月，首次开票金额不能超过月核定额度/3元/n您提交的发票数据中，单张金额均大于该金额，将导致开票失败，请您重新填写开票申请，或勾选低于月核定额度/3元的开票申请同步结算！',  //内容
        okText: '',    //确定文字
        okType: '',    //确定类型
        cancleText: '关闭',    //取消文字
        cancleType: 'primary',    //取消类型
        source: 3,    //来源  1-申请开票（首次开票金额限制）  2-申请开票（单次开票金额限制）  3-提交结算（首次开票金额限制）
      }
    }
  },
  created() {
    if (this.$route.query.bizId){
      let bizId = this.$route.query.bizId;
      this.getTableData(bizId);
    }else{
      this.getTableData();
    }
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        // hideDefaultSelections: true,
        //控制全选是否展示
        columnTitle: this.businessStatus == 117 ? ' ' : '',
        getCheckboxProps: record => ({
          props: {
            disabled: record.studerType == 1,
          }
        })
      };
    },
  },
  watch: {
    selectedRows: {
      handler: function (val) {
        // console.log(val)
        this.tableData = [...this.tableData]
        this.$forceUpdate()
      },
      deep: true,
      immediate: true
    }
  },
  methods:{
    reload(){
      this.goPageEvent(this.pageKey)
    },
    //待结算状态的同一企业 可结算数据
    onSelectChange(selectedRowKeys, selectedRows){
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      // this.SelectChangeEvent(selectedRows)

      if(this.businessStatus == 117){
        if(selectedRows.length>0){
          const newList = this.findIndicesNotContainingValue(this.entIdList,selectedRows[0].entId);
          for(let a=0;a<newList.length;a++){
            this.tableData[newList[a]].studerType = 1;
          }
        }else{
          for(let a=0;a<this.tableData.length;a++){
            this.tableData[a].studerType = 0;
          }
        }
      }
    },
    //查询展开收起
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    //查询
    handleSearch(){
      this.page.currentPage = 1;
      this.clearBox();
      this.getTableData();
    },
    //重置
    handleReset(){
      this.page.currentPage = 1;
      this.filterList = {};//清空查询条件
      this.clearBox();
      this.getTableData();//重置列表
    },
    //选择页数
    onPageChange(newPage) {
      this.page.currentPage = newPage;
      this.getTableData()
    },
    // 页面变化
    onSizeChange(current, newSize) {
      this.page.pageSize = newSize;
      this.getTableData()
    },
    //详情
    toDetails(record){
      this.$router.push({
        path: '/invoice/invoiceRecord',
        query:{
          bizId: record.id
        }
      })
    },
    //-------------------------首次获取表格数据  start ↓------------------
    //首次获取表格数据
    getTableData(bizId){
      this.clearBox();
      this.loading = true;
      let params = {};
      params.data = this.filterList;
      params.data.status = 1;  // 1 新开票 2 退票 3 退票-错票
      params.data.bizStatus = this.businessStatus;

      bizId ? params.data.entId = bizId : ""

      params.pageNo = this.page.currentPage;
      params.pageSize = this.page.pageSize;

      const setData = (dataList)=>{
        const tempObj = {
          entIdGroup:{},//
          dataList:[],
        }
        dataList.forEach((item,index)=>{
          const {entId} = item
          tempObj.dataList.push({...item,studerType:0})
          if(tempObj.entIdGroup[entId]){
            tempObj.entIdGroup[entId].push(index)
          }else{
            tempObj.entIdGroup[entId] = [index]
          }
        })
        return tempObj
      }

      getTaxInvoiceList(params).then(res => {
        if (res.success) {
          this.entIdList = [];
          let data = res.result || {};
        //  const res_= setData(data.records)
          for(let a=0;a<data.records.length;a++){
            data.records[a].studerType = 0;
            this.entIdList.push(data.records[a].entId);
          }
          // 赋值表格数据
          this.tableData = data.records || [];
          // this.studerTypeObj = res_
          // this.tableData = res_.dataList;

          //检查列表数据是否包含开票失败的票 errorFlag   1 无错误 2 开票人错误 3 其他错误
          let arr1 = this.tableData.filter(item => item.errorFlag > 1);
          if (arr1.length > 0){
            this.revokeFlagStatus = true;
          }else{
            this.revokeFlagStatus = false;
          }

          // 赋值总条数
          this.page.totalCount = data.total || 0;
          this.loading = false;
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    clearBox(){
      this.selectedRowKeys = [];
      this.selectedRows = [];
    },
    SelectChangeEvent(selectedRows){
      if(this.businessStatus != 117){
        return false
      }
      if(!this.isType.isEmpty(selectedRows)){
        const {entId} = selectedRows[0]
        for (const key in this.studerTypeObj.entIdGroup) {
          if(key !=entId){
            this.studerTypeObj.entIdGroup[key].forEach(item=>{
              this.tableData[item].studerType = 1;
            })
          }else{
            this.studerTypeObj.entIdGroup[key].forEach(item=>{
              this.tableData[item].studerType = 0;
            })
          }
        }
      }else{
        this.tableData.forEach(item=>{
          item.studerType = 0;
        })
      }
    },
    //-----------------------发票领用数量弹层（作废）  start ↓-------------
    //调用父组件  （下一步）
    handleUseFather(useData){
      //处理返回数据
      let str = {};
      let newArr = [];
      str.numPd = useData.pd;
      str.numPz = useData.pz;
      str.numZd = useData.zd;
      str.numZz = useData.zz;
      str.entId = this.theData.entId;
      str.action = 1;  // 1 领取 2 使用
      newArr.push(str);  //往数组追加

      this.undeleteInfo.blInvcList = newArr;

      this.collecteCancle();  //弹层关闭
      this.undeleteOperate(); //调用删除接口
    },
    //领用弹层取消
    collecteCancle(){
      this.undeleteInfo.isCollecteShow = false;
    },
    //-----------------------发票领用数量弹层（作废）  end ↑---------------
  }
}
</script>

<style lang="less">
.table-action{
  display: flex;
  justify-content: center;
  align-items: center;
  .ant-btn-link{
    padding: 0 2px;
  }
  .ant-divider-vertical{
    width: 1px;
  }
}
</style>
